package bigdata.monitor.binlog.utils;

import com.baomidou.dynamic.datasource.annotation.DS;
import bigdata.monitor.binlog.entity.MonitorRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 执行 Doris 综合校验，返回未通过的规则
 */
@Slf4j
@Component
public class RuleEvaluator {

    @Autowired
    private JdbcTemplate dorisJdbcTemplate;

    /**
     * 在 Doris 数据源上执行规则校验
     */
    @DS("doris") // 切换到 Doris 数据源
    public List<MonitorRule> evaluateRules(String binlogJson, List<MonitorRule> rules) {
        if (rules.isEmpty()) return Collections.emptyList();

        String sql = CombinedRuleSqlBuilder.buildSql(binlogJson, rules);
        Map<String, Object> resultMap;
        try {
            resultMap = dorisJdbcTemplate.queryForMap(sql);
        } catch (Exception e) {
            log.error("Doris evaluation failed. SQL: {}", sql, e);
            return Collections.emptyList();
        }

        List<MonitorRule> failedRules = new ArrayList<>();
        for (MonitorRule rule : rules) {
            Object value = resultMap.get(rule.getRuleCode());
            if (isTrue(value)) {
                failedRules.add(rule);
            }
        }
        return failedRules;
    }

    private boolean isTrue(Object value) {
        if (value == null) return false;

        // 处理 BOOLEAN 类型 (true/false)
        if (value instanceof Boolean) {
            return (Boolean) value;
        }

        // 处理 INTEGER 类型 (1/0)
        if (value instanceof Number) {
            return ((Number) value).intValue() == 1;
        }

        // 处理 STRING 类型 ("true"/"false" 或 "1"/"0") - 安全兜底
        if (value instanceof String) {
            String str = ((String) value).toLowerCase();
            return "true".equals(str) || "1".equals(str);
        }

        return false;
    }
}
